package com.swordget.dao.impl;

import com.swordget.commons.JdbcUtil;
import com.swordget.dao.CheckLogDao;
import com.swordget.entity.vo.CheckLogVo;
import com.swordget.exception.VerifyFailException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @Author: David
 * @Date: Created in 15:03 2020/5/7
 * @Description:
 * @Modified By:
 * @Version:
 */
@Repository
public class CheckLogDaoImp implements CheckLogDao {

    private JdbcUtil jdbcUtil;

    @Autowired
    public CheckLogDaoImp(JdbcUtil jdbcUtil) {
        this.jdbcUtil = jdbcUtil;
    }

    @Override
    public boolean modify(CheckLogVo checkLogVo, String tableName, List<String> columns) {
        //生成审核语句
        StringBuffer buffer = new StringBuffer();
        buffer.append("UPDATE CHECKLOG SET TABLEID = '");
        buffer.append(checkLogVo.getTableId());
        buffer.append("', CREATEUSER = '");
        buffer.append(checkLogVo.getCreateUser());
        buffer.append("', MAKEUSER = '");
        buffer.append(checkLogVo.getMakeUser());
        buffer.append("', MAKESTATUS= '");
        buffer.append(checkLogVo.getMakeStatus());
        buffer.append("', CREATEDATE='");
        buffer.append(checkLogVo.getCreateDate());
        buffer.append("', CREATETIME = '");
        buffer.append(checkLogVo.getCreateTime());
        buffer.append("', MAKEDATE = '");
        buffer.append(checkLogVo.getMakeDate());
        buffer.append("', MAKETIME = '");
        buffer.append(checkLogVo.getMakeTime());
        buffer.append("' WHERE SERIALNO = '");
        buffer.append(checkLogVo.getSerialNo());
        buffer.append("'");

        if (checkLogVo.getMakeStatus().equals("1")) {
            String deleteCommand = String.format("DELETE FROM %s WHERE IMPORTID = '%s'", tableName, checkLogVo.getSerialNo());
            return jdbcUtil.executeBatch(buffer.toString(), deleteCommand);
        } else if (checkLogVo.getMakeStatus().equals("2")) {
            String checkCommand = String.format("INSERT INTO %s(%s) SELECT %s FROM %s WHERE IMPORTID = '%s'",
                    tableName, String.join(",", columns), String.join(",", columns), tableName , checkLogVo.getSerialNo());
            String deleteCommand = String.format("DELETE FROM %s WHERE IMPORTID = '%s'", tableName, checkLogVo.getSerialNo());
            return jdbcUtil.executeBatch(buffer.toString(), checkCommand, deleteCommand);
        } else {
            throw new VerifyFailException("无法获取审核状态!");
        }
    }
}
